package com.ljf.game.event;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ljf.game.WebsocketManager;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 描述 :
 *
  {
  "EVENT_CLASS":"GROUP_CHAT",
  "HOME_OWNER":"admin",
  "CHAT_MESSAGE":"帅哥你好"
  }
 *
 * <p>
 * 版本     作者     时间      内容
 * 1.0      lijinfeng       2025-05-10 21:09     create
 */
public class GroupChatEvent extends AbstractEvent{
    @Override
    void run(WebSocketSession session, String text) {

        StringBuilder result = new StringBuilder();
        HashMap<String, Object> hashMap = EventManager.getResultMap(text);


        String username = WebsocketManager.getUsername(session);
        JSONObject jsonObject =  JSON.parseObject(text);
        String homeowner = jsonObject.get("HOME_OWNER").toString();
        String chatMessage = jsonObject.get("CHAT_MESSAGE").toString();

        ConcurrentHashMap<String, WebSocketSession> roomMap =  WebsocketManager.groupGet(homeowner);

        if(null == roomMap || roomMap.isEmpty()){
            WebsocketManager.sendMessage(session, hashMap, "房间 [" + homeowner + "] 不存在");
            return;
        }

        // 房间存在
        result.append(chatMessage);
        hashMap.put("SENDER",username);
        WebsocketManager.sendMessageToAll(roomMap, hashMap, result.toString());

    }
}
